package com.example.jetpackstu.ui.news

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AlertDialog
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.jetpackstu.R
import com.example.jetpackstu.databinding.FragmentListBinding
import com.example.jetpackstu.logic.entity.News

class ListFragment : Fragment() {

    private var _binding: FragmentListBinding? = null

    private val binding get() = _binding!!

    private lateinit var mAdapter: NewsAdapter

    private val mModel: ListViewModel by viewModels()

    private val navController get() = findNavController()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = DataBindingUtil.inflate(inflater, R.layout.fragment_list, container, false)
        initView()
        initListener()
        initData()
        return binding.root
    }

    private fun initData() {
        mModel.allNews.observe(
            viewLifecycleOwner
        ) { data -> mAdapter.setNewInstance(data?.toMutableList()) }
    }

    private fun initListener() {
        binding.btnAdd.setOnClickListener {
            val action =
                ListFragmentDirections.actionListFragmentToDetailFragment(-1)
            navController.navigate(action)
        }
        mAdapter.setOnItemChildClickListener { adapter, view, position ->
            val item = adapter.getItem(position) as News
            when (view.id) {
                R.id.btn_del -> {
                    context?.let {
                        AlertDialog.Builder(it).setMessage("确认删除吗？").setPositiveButton(
                            "确认"
                        ) { dialog, _ ->
                            mModel.delNews(item.id)
                            dialog.dismiss()
                        }
                            .setNegativeButton("取消") { dialog, _ ->
                                // 删除
                                dialog.dismiss()
                            }.show()
                    }
                }
                R.id.btn_edit -> {
                    val action =
                        ListFragmentDirections.actionListFragmentToDetailFragment(item.id)
                    navController.navigate(action)
                }
                else -> {}
            }
        }
    }

    private fun initView() {
        binding.lifecycleOwner = this
        mAdapter = NewsAdapter(mutableListOf())
        binding.rvNewsList.run {
            adapter = mAdapter
            layoutManager = LinearLayoutManager(context)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        _binding = null
    }
}